package com.zhaoc.service.impl;

import com.zhaoc.dao.MenuRepository;
import com.zhaoc.domain.system.Menu;
import com.zhaoc.domain.system.User;
import com.zhaoc.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>title:com.zhaoc.service.impl</p>
 * date:2018/8/22 0022
 * time:19:57
 * author:赵成
 * user:13566
 */
@Service
@Transactional
public class MenuService implements IMenuService {

    @Autowired
    private MenuRepository menuRepository;

    //查询所有菜单
    @Override
    public List<Menu> findAll() {
        return menuRepository.findAll();
    }

    //添加菜单
    @Override
    @CacheEvict(value = "menu")
    public void save(Menu menu) {
        //防止用户没有选择父菜单
        if (menu.getParentMenu() != null && menu.getParentMenu().getId() == 0){
            menu.setParentMenu(null);
        }
        menuRepository.save(menu);
    }

    //根据用户角色查询菜单
    @Override
    @Cacheable("menu")
    public List<Menu> finfByUser(User user) {
        if (user.getUsername().equals("admin")){
            //如果是管理员,则显示所有菜单
            return menuRepository.findAll();
        }else {

        return menuRepository.findByUser(user.getId());
        }
    }
}
